package cn.kgc.controller;

import cn.kgc.client.RestDmUserClient;
import cn.kgc.dto.Dto;
import cn.kgc.dto.DtoUtil;
import cn.kgc.pojo.DmUser;
import cn.kgc.service.UserService;
import cn.kgc.utils.BaseException;
import cn.kgc.utils.MD5;
import cn.kgc.vo.TokenVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.ExecutionException;

@RestController
@RequestMapping("/user/api")
public class UserController {

    @Resource
    RestDmUserClient restDmUserClient;

    @Resource
    UserService userService;


    /**
     * 实现账号密码登录
     * @param phone
     * @param password
     * @return
     * @throws Exception
     */
    @RequestMapping("/p/login")
    public Dto Login(@RequestParam String phone, @RequestParam String password) throws Exception {
        //入参进行操作
        String secretPassword = MD5.getMd5(password, 32);

        //实现登录的操作
        Object[] objects = userService.queryLogin(phone, secretPassword);

        return DtoUtil.returnDataSuccess(objects);
    }

    /**
     * Token置换
     * @param token
     * @return
     * @throws BaseException
     */
    @RequestMapping("/v/replaceToken")
    public Dto replaceToken(@RequestHeader String token) throws BaseException {
        TokenVo tokenVo= userService.replaceToken(token);
        return DtoUtil.returnDataSuccess(tokenVo);
    }

    /**
     * 发送登录验证码
     * 这个接口只需要发送短信，报错，自定异常直接返回
     * @param phone
     * @return
     */
    @RequestMapping("/p/logincode")
    public Dto sendPhoneCode(@RequestParam String phone) throws BaseException, ExecutionException, InterruptedException {
        userService.sendLoginCode(phone);
        return DtoUtil.returnSuccess();
    }

    /**
     *  短信验证码校验
     * @param phone
     * @param vcode
     * @return
     */
    @RequestMapping("p/phonelogin")
    public Dto validPhoneCode(@RequestParam  String phone, @RequestParam String vcode) throws Exception {
        Object[] objects= (Object[]) userService.checkPhoneLoginCode(phone,vcode);
        return DtoUtil.returnDataSuccess(objects);
    }
}
